<?php

class Meetings
{
	public $pdo;
	
	public function get_by_group($group)
	{
		$stmt = $this->pdo->prepare("SELECT ID,
			                          extract(epoch FROM START_TIME) AS DATE,
			                          extract(epoch FROM START_TIME) AS START_TIME,
			                          extract(epoch FROM END_TIME) AS END_TIME,
			                          LOCATION
			                          FROM MEETINGS
			                          WHERE GROUPS = ?
			                          ORDER BY DATE, START_TIME ASC");
		$stmt->execute(array($group));
		return $stmt->fetchAll(PDO::FETCH_CLASS);
	}

	public function insert($group,$date,$start_time,$end_time,$location)
	{
		$error = "<ul class='error'>";
		if(!strtotime($date))
			$error .= "<li>Anna päivämäärä muodossa pp.kk.vvvv</li>";
		if(!strtotime($date . " " . $start_time))
			$error .= "<li>Anna alkuaika muodossa tt:ss</li>";
		if(!strtotime($date . " " . $end_time))
			$error .= "<li>Anna päättymisaika muodossa tt:ss</li>";
		if(strtotime($start_time) > strtotime($end_time))
			$error .= "<li>Alkamisajan tulee olla alle päättymisajan</li>";
	
		if(strcmp($error,"<ul class='error'>") != 0)
		{
			$error .= "</ul>";
			return $error;
		}
		else
		{	
			$start_time = $date . " " . $start_time;
			$end_time   = $date . " " . $end_time;
		
			$stmt = $this->pdo->prepare("INSERT INTO MEETINGS (GROUPS,START_TIME,END_TIME,LOCATION) VALUES (?,?,?,?)");
			return $stmt->execute(array($group,$start_time,$end_time,$location));
		}
	}

	public function update($meeting,$date,$start_time,$end_time,$location)
	{
		$error = "<ul class='error'>";
		if(!strtotime($date))
			$error .= "<li>Anna päivämäärä muodossa pp.kk.vvvv</li>";
		if(!strtotime($date . " " . $start_time))
			$error .= "<li>Anna alkuaika muodossa tt:ss</li>";
		if(!strtotime($date . " " . $end_time))
			$error .= "<li>Anna päättymisaika muodossa tt:ss</li>";
		if(strtotime($start_time) > strtotime($end_time))
			$error .= "<li>Alkamisajan tulee olla alle päättymisajan</li>";
	
		if(strcmp($error,"<ul class='error'>") != 0)
		{
			$error .= "</ul>";
			return $error;
		}
		else
		{
			$start_time = $date . " " . $start_time;
			$end_time   = $date . " " . $end_time;
		
			$stmt = $this->pdo->prepare("UPDATE MEETINGS SET (START_TIME,END_TIME,LOCATION) = (?,?,?) WHERE ID = ?");
			return $stmt->execute(array($start_time,$end_time,$location,$meeting));
		}
	}

	public function delete($meeting)
	{
		$stmt = $this->pdo->prepare("DELETE FROM MEETINGS WHERE ID = ?");
		return $stmt->execute(array($meeting));
	}
}

?>
